package com.sina.microblog.api
{
	import com.abstract.IWeiboAPI;
	import com.events.WeiboEvent;
	import com.utils.StringEncoders;
	import com.sina.microblog.utils.URLUtil_wb;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import flash.net.navigateToURL;
	
	public class WeiboAPI extends AbstractAPI_wb implements IWeiboAPI
	{
		public function WeiboAPI()
		{
			super();
		}
		
		private var _type:String;
		
		public function callWeiboAPI(type:String, params:Object):void
		{
			_type = type;
			var method:String = WeiboUrlMethodUtil.config[type].method;
			var url:String = config.baseURL + WeiboUrlMethodUtil.config[type].url + '.' + config.dataFormat;
			switch(type){
				case 'requestToken':
				case 'accessToken':
					url = config.baseURL + WeiboUrlMethodUtil.config[type].url;
					break;
				default:
			}
			loadUrl(url,params,method);
//			loadUrl(url,params,method);
		}
		
		override protected function completeHandler(event:Event):void{
			super.completeHandler(event);			
			switch(_type){
				case 'requestToken':
				case 'accessToken':
					requestTokenHandler(event);
					break;
//					accessTokenHandler(event);
//					break;
				default:
					var evt:WeiboEvent = new WeiboEvent(WeiboEvent.RESULT);
					evt.object = {result:data,type:_type};
					dispatchEvent(evt);
					break;
			}
		}
		
		/**
		 * @private
		 */		
		private function requestTokenHandler(event:Event):void
		{
			var needRequestAuthorize:Boolean = config.accessTokenKey.length == 0;
			var result:String = event.currentTarget.data as String;
			if (result.length > 0)
			{
				var urlVar:URLVariables=new URLVariables(event.currentTarget.data);
				config.accessTokenKey=urlVar.oauth_token;
				config.accessTokenSecret=urlVar.oauth_token_secret;
				if (needRequestAuthorize)
				{
					openUserAuthPage();
					needRequestAuthorize=false;
				}
				else
				{
//					var e:MicroBlogEvent=new MicroBlogEvent(MicroBlogEvent.OAUTH_CERTIFICATE_RESULT);
//					e.result={oauthTokenKey: _accessTokenKey, oauthTokenSecrect: _accessTokenSecret};
//					dispatchEvent(e);
//					verifyCredentials();
				}
			}
			(event.target as EventDispatcher).removeEventListener(Event.COMPLETE,requestTokenHandler);
		}
		
		/**
		 * 打开用户授权页面
		 * @param pageTarget 窗口模式，默认是_self
		 */			
		public function openUserAuthPage(pageTarget:String="_self"):void
		{
			var url:String=config.baseURL + config.authorizeURL;
			url+="?oauth_token=" + StringEncoders.urlEncodeUtf8String(config.accessTokenKey);
			url+="&oauth_callback=oob";
			navigateToURL(new URLRequest(url), "_blank");
		}
		
	}
}